﻿using System;

namespace UniRx.Operators
{
	// Token: 0x020002AF RID: 687
	internal class FromEventObservable<TDelegate, TEventArgs> : OperatorObservableBase<TEventArgs>
	{
		// Token: 0x06000F00 RID: 3840 RVA: 0x00046032 File Offset: 0x00044432
		public FromEventObservable(Func<Action<TEventArgs>, TDelegate> conversion, Action<TDelegate> addHandler, Action<TDelegate> removeHandler) : base(false)
		{
			this.conversion = conversion;
			this.addHandler = addHandler;
			this.removeHandler = removeHandler;
		}

		// Token: 0x06000F01 RID: 3841 RVA: 0x00046050 File Offset: 0x00044450
		protected override IDisposable SubscribeCore(IObserver<TEventArgs> observer, IDisposable cancel)
		{
			FromEventObservable<TDelegate, TEventArgs>.FromEvent fromEvent = new FromEventObservable<TDelegate, TEventArgs>.FromEvent(this, observer);
			return (!fromEvent.Register()) ? Disposable.Empty : fromEvent;
		}

		// Token: 0x040008B1 RID: 2225
		private readonly Func<Action<TEventArgs>, TDelegate> conversion;

		// Token: 0x040008B2 RID: 2226
		private readonly Action<TDelegate> addHandler;

		// Token: 0x040008B3 RID: 2227
		private readonly Action<TDelegate> removeHandler;

		// Token: 0x020002B0 RID: 688
		private class FromEvent : IDisposable
		{
			// Token: 0x06000F02 RID: 3842 RVA: 0x0004607B File Offset: 0x0004447B
			public FromEvent(FromEventObservable<TDelegate, TEventArgs> parent, IObserver<TEventArgs> observer)
			{
				this.parent = parent;
				this.observer = observer;
			}

			// Token: 0x06000F03 RID: 3843 RVA: 0x00046094 File Offset: 0x00044494
			public bool Register()
			{
				this.handler = this.parent.conversion(new Action<TEventArgs>(this.OnNext));
				try
				{
					this.parent.addHandler(this.handler);
				}
				catch (Exception error)
				{
					this.observer.OnError(error);
					return false;
				}
				return true;
			}

			// Token: 0x06000F04 RID: 3844 RVA: 0x00046108 File Offset: 0x00044508
			private void OnNext(TEventArgs args)
			{
				this.observer.OnNext(args);
			}

			// Token: 0x06000F05 RID: 3845 RVA: 0x00046118 File Offset: 0x00044518
			public void Dispose()
			{
				if (this.handler != null)
				{
					this.parent.removeHandler(this.handler);
					this.handler = default(TDelegate);
				}
			}

			// Token: 0x040008B4 RID: 2228
			private readonly FromEventObservable<TDelegate, TEventArgs> parent;

			// Token: 0x040008B5 RID: 2229
			private readonly IObserver<TEventArgs> observer;

			// Token: 0x040008B6 RID: 2230
			private TDelegate handler;
		}
	}
}
